package ycj.learn.spring.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;

@Configuration
public class CglibDynamicProxyTest {


    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(CglibDynamicProxyTest.class);



        for (String name : context.getBeanDefinitionNames()) {

            System.out.println(name);
        }

        IHelloWorld proxy = createProxy();
        proxy.sayHello("Cglib proxy say hello");

    }

    private static IHelloWorld createProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(IHelloWorld.class);
        enhancer.setInterceptDuringConstruction(false);
        enhancer.setUseCache(false);

        enhancer.setCallback(new MethodInterceptor() {
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                System.out.println("Executed method:" + method.getName());
                for (Object obj : objects) {
                    System.out.println(obj);
                }

                return null;
            }
        });

        return (IHelloWorld) enhancer.create();
    }

}
